/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.quantum.jbencoder.types;

import java.io.*;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author g073025
 */
public class BencodedDictionnary extends BencodedPrimitiveType {

    private Map<BencodedString, BencodedType> dictionnary = new HashMap<BencodedString, BencodedType>();
    private final byte prefix = 'd';

    @Override
    protected void writePrefix(OutputStream os) throws IOException {
        os.write(prefix);
    }

    @Override
    protected void writeValue(OutputStream os) throws IOException {
        Iterator iterator = dictionnary.keySet().iterator();

        while (iterator.hasNext()) {
            BencodedString key = (BencodedString) iterator.next();
            BencodedType value = (BencodedType) dictionnary.get(key);
            key.serialize(os);
            value.serialize(os);
        }
    }

    @Override
    protected void writeSuffix(OutputStream os) throws IOException {
        os.write(suffix);
    }

    /**
     * adding key-value pair into dictionnary
     *
     * @param key
     * @param value
     */
    public void put(BencodedString key, BencodedType value) {
        this.dictionnary.put(key, value);
    }

    /**
     * return true if key exists into dictionnary, false else
     *
     * @param key
     * @return
     */
    public boolean containsKey(final BencodedString key) {
        return this.dictionnary.containsKey(key);
    }

    /**
     * return BencodedType value mapped with bencodedString key, null otherwise
     *
     * @param key
     * @return
     */
    public BencodedType getValue(final BencodedString key) {
        for (BencodedString szKey : this.dictionnary.keySet()) {
            if (szKey.getValue().equalsIgnoreCase(key.getValue())) {
                return this.dictionnary.get(szKey);
            }
        }
        return null;

    }

    @Override
    public void deserialize(InputStream is) throws IOException {
        //read byte by byte the stream until the end 
        Reader in = new InputStreamReader(is, "UTF-8");
        char[] buf = new char[1];
        int n;
        in.read(buf);
        if (buf[0] == prefix) {
            in.read(buf);
            if (buf[0] == suffix) {
                //done
            } else {
                //read key
                System.out.println("reading key");
                //read value
                System.out.println("reading value");
            }
        } else {
            throw new IOException("unexpected prefix " + buf);
        }

    }
}
